import store from '../../store/index'

export default {

  socket: null,
  alarmWs: `ws://${window.global_url.Base_url}:8080/system/websocket/alarmPush.do`,
  servicePort: 8002,
  socketPort: 8762,
  socketYFPort: 12345,
  isConnect: true, // 是否断开连接
  init: function() {
    if (typeof (WebSocket) === 'undefined') {
      alert('您的浏览器不支持socket')
    } else {
      // 实例化socket
      this.socket = new WebSocket(this.alarmWs)
      // 监听socket连接
      this.socket.onopen = this.open
      // 监听socket错误信息
      this.socket.onerror = this.error
      this.socket.onclose = this.close
      // 监听socket消息
      this.socket.onmessage = this.getMessage
    }
  },

  getState: function() {
    return this.socket.readyState
  },
  open: function() {
    console.log('socket连接成功')
  },
  error: function(e) {
    const that = this
    console.log('连接错误', e)
    that.isConnect = false // 连接断开修改标识
    that.restart() // 连接错误 需要重连
  },
  getMessage: function(msg) {
    store.commit('wsData/UPDATE_BELLMSG', msg)
  },
  send: function(params) {
    // console.log('ws发送数据', params, this.socket.OPEN, this.socket.CONNECTING)
    this.socket.send(params)
  },
  close: function(e) {
    console.log('socket已经关闭', e)
  },

  // 重新连接
  restart() {
    console.log('正在重新连接websocket', this.socket)
    this.socket.init()
  },

  destroyed: function() {
    // 销毁监听
    this.socket.onclose = this.close
  }
}
